package net.xdclass.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.ClientTypeEnum;
import net.xdclass.enums.ProductOrderPayTypeEnum;
import net.xdclass.request.ConfirmOrderRequest;
import net.xdclass.service.ProductOrderService;
import net.xdclass.util.JsonData;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 二当家小D
 * @since 2021-06-04
 */
@Slf4j
@Api(tags = "订单模块")
@RestController
@RequestMapping("/api/order/v1")
public class ProductOrderController {

    @Autowired
    private ProductOrderService productOrderService;

    @GetMapping("query_state")
    public JsonData queryProductOrderState(@RequestParam("out_trade_no") String outTradeNo){
        String state = productOrderService.queryProductOrderState(outTradeNo);
        return StringUtils.isBlank(state) ? JsonData.buildResult(BizCodeEnum.ORDER_CONFIRM_NOT_EXIST) : JsonData.buildSuccess(state);
    }


    @ApiOperation("提交订单")
    @PostMapping("confirm")
    public void confimOrder(@RequestBody ConfirmOrderRequest confirmOrderRequest,
                            HttpServletResponse response) {
        JsonData jsonData = productOrderService.confirmOrder(confirmOrderRequest);
        if (jsonData.getCode() == 0) {
            String clientType = confirmOrderRequest.getClientType();
            String payType = confirmOrderRequest.getPayType();
            //如果是支付宝网页支付， 都是跳转网页。app除外
            if (ProductOrderPayTypeEnum.ALIPAY.name().equalsIgnoreCase(payType)) {
                if (ClientTypeEnum.H5.name().equalsIgnoreCase(clientType)) {
                    log.info("创建支付宝订单成功{}", confirmOrderRequest.toString());
                    writeData(response,jsonData);
                }else if(ClientTypeEnum.APP.name().equalsIgnoreCase(clientType)) {
                    // app sdk支付 TODO
                }

            } else if (ProductOrderPayTypeEnum.WECHAT.name().equalsIgnoreCase(payType)) {
                //微信支付  TODO
            }
        }else{
            log.error("创建订单失败{}",jsonData.toString());
        }
    }

    private void writeData(HttpServletResponse response, JsonData jsonData) {
        try {
            response.setContentType("text/html;charset=UTF8");
            response.getWriter().write(jsonData.getData().toString());
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            log.error("写出html异常",e);
        }
    }
}

